package com.atom.module.author.config;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;

@Slf4j
@Component
@RequiredArgsConstructor
public class AuthorTableInitializer implements CommandLineRunner {

    private final DataSource dataSource;
    private final Environment environment;

    @Override
    public void run(String... args) throws Exception {
        // 可加一个配置开关：auth.auto-init-tables=true/false
        if (!isEnabled()) return;

        Resource resource = new ClassPathResource("db/migration/V1__init_schema.sql");
        if (!resource.exists()) return;

        String sql = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
        try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) {
            for (String statement : sql.split(";")) {
                String trimmed = statement.trim();
                if (!trimmed.isEmpty() && !trimmed.startsWith("--")) {
                    stmt.execute(trimmed);
                }
            }
        }
    }

    private boolean isEnabled() {
        // 可通过 Environment 读取配置，例如：
        return environment.getProperty("author.auto-init-tables", Boolean.class, true);
    }

}
